package cn.sirun.com.fca.personal.center.model.service;

import android.app.Application;
import android.content.Context;

import com.tencent.cloud.iov.util.ThreadUtils;

import cn.sirun.com.fca.account.service.LoginManager;
import cn.sirun.com.fca.account.service.LoginStatusListener;
import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;

/**
 * 个人中心服务类
 *
 * @author showxiao
 * @date 2018/10/18
 */
public final class PersonalCenterServices {

    private static Context sContext;
    private static BehaviorSubject<Boolean> sDestroySubject;

    public static Context getContext() {
        return sContext;
    }

    /**
     * 初始化个人中心模块
     *
     * @param application
     */
    public static void init(Application application) {
        sContext = application.getApplicationContext();

        observeLoginStatus();
    }

    /**
     * 监听用户登录态
     */
    private static void observeLoginStatus() {
        LoginManager.getInstance().addLoginStatusListener(new LoginStatusListener() {
            @Override
            public void onLoginStatusInvalid() {
                // do nothing
            }

            @Override
            public void onLoggedOut() {
                // to nothing
            }

            @Override
            public void onAccountChanged() {
//                synchronized (CarServices.class) {
//                    ThreadUtils.executeOnIoThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            onDestroy();
//                            PersonalInfoManager.clearLocalPersonalInfo();
//                        }
//                    });
//                }
            }
        });
    }

    /**
     * 通知销毁的数据源
     *
     * @return
     */
    public static synchronized Observable<Boolean> getDestroyObservable() {
        if (sDestroySubject == null) {
            sDestroySubject = BehaviorSubject.create();
        }
        return sDestroySubject.hide();
    }

    /**
     * 通知销毁事件
     */
    public static synchronized void onDestroy() {
        if (sDestroySubject != null) {
            sDestroySubject.onNext(true);
            sDestroySubject = null;
        }
    }

    private PersonalCenterServices() {}

}
